package com.dys.controller;

import com.dys.common.ResponseResult;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: 疾风
 * @ClassName: AuthorizeController
 * @Description: 权限拓展控制器
 * @CreateDate: 2024/12/17
 * @Version: v1.0.0
 */
@RestController
@RequestMapping(value = {"/authorize"})
public class AuthorizeController {

    /**
     * hasAuthority: 检查调用者是否具有指定的权限
     */
    @PreAuthorize(value = "hasAuthority('system:user:list')")
    @GetMapping(value = "/hasUserList")
    public ResponseResult<Object> hasUserList() {
        return new ResponseResult<>(200, "响应成功", "包含指定权限：system:user:list");
    }

    /**
     * hasAnyAuthority: 检查调用者是否具有指定的一个权限即可
     */
    @PreAuthorize(value = "hasAnyAuthority('system:user:list','system:role:list')")
    @GetMapping(value = "/hasUserOrRoleList")
    public ResponseResult<Object> hasUserOrRoleList() {
        return new ResponseResult<>(200, "响应成功", "拥有指定权限中的一个权限即可：system:user:list,system:role:list");
    }

    /**
     * hasRole: 检查调用者是否有指定的角色
     * asRole要求有对应的角色才可以访问，但是它内部会把我们传入的参数拼接上 ROLE_
     * 后再去比较。所以这种情况下要用户对应的权限也要有 ROLE_ 这个前缀才可以
     */
    @GetMapping(value = {"/hasRoleAdmin"})
    @PreAuthorize(value = "hasRole('admin')")
    public ResponseResult<Object> hasRoleAdmin() {
        return new ResponseResult<>(200, "响应成功", "拥有指定的角色：admin");
    }

    /**
     * hasAnyRole: 检查调用者是否具有指定的一个角色即可
     */
    @GetMapping(value = {"/hasRoleAdminOrCommon"})
    @PreAuthorize(value = "hasAnyRole('admin','common')")
    public ResponseResult<Object> hasRoleAdminOrCommon() {
        return new ResponseResult<>(200, "响应成功", "拥有指定角色中的一个角色即可：admin,common");
    }

    /**
     * 使用Spel表达式,引入自定义的权限校验
     */
    @GetMapping(value = {"/customAuthority"})
    @PreAuthorize(value = "@my_ex.hasAuthority('system:user:list')")
    public ResponseResult<Object> customAuthority() {
        return new ResponseResult<>(200, "响应成功", "自定义权限校验");
    }

    /**
     * 基于配置的权限校验规则
     */
    @GetMapping(value = {"/securityConfigAuthority"})
    public ResponseResult<Object> securityConfigAuthority(){
        return new ResponseResult<>(200, "响应成功", "基于Security配置的权限校验");
    }
}
